import {createSlice, configureStore} from '@reduxjs/toolkit';
import {nanoid, customAlphabet} from 'nanoid/non-secure';
import deepMemryJson from '@/fun/deepMemryJson';

function create(defaultValue) {
  const slice = createSlice({
    name: customAlphabet('abcdefghijklmnopqrstuvwxyz', 20)(),
    initialState: {
      value: defaultValue,
    },
    reducers: {
      setValue: (state, action) => {
        state.value = action.payload;
      },
    },
  });
  return [slice.reducer, slice.actions.setValue];
}

//静态配置
export const [staticConfig] = create({
  toolsHeight: 40,
});
//组件key（重置业务数据使用）
export const [comKey, setComkey] = create('init');

//路由对象数据
export const [routeData, setRouteDate] = create({});

//账号
export const [accountInfo, setAccountInfo] = create({});

//登录token
export const [token, setToken] = create('');

//更新账号信息key
export const [keyGetAccountInfo, setKeyGetAccountInfo] = create(1);

//安全距离
export const [safeAreaData, setSafeAreaData] = create({});

//设置信息
export const [deviceInfo, setDeviceInfo] = create({});

//业务数据（深度合并）
export const setJsonBusMerry = (params = {}) => {
  return (dispatch, getSate) => {
    const state = getSate();
    let oldValue = state.jsonBus.value;
    let newValue = JSON.parse(JSON.stringify(oldValue));
    deepMemryJson(newValue, params);
    dispatch(setJsonBusOrigin(newValue));
  };
};

//页面背景色
export const [pageBackgroundColor, setPageBackgroundColor] = create('#FFF');
//头部背景色
export const [headerBackgroundColor, setHeaderBackgroundColor] = create('#FFF');
//内容背景色
export const [contentBackgroundColor, setContentBackgroundColor] =
  create('#f9f9f9');
//App状态变化： active - 应用正在前台运行，background - 应用正在后台运行
export const [appRunState, setAppRunState] = create();

export default () => {
  return configureStore({
    reducer: {
      staticConfig,
      comKey,
      routeData,
      accountInfo,
      token,
      keyGetAccountInfo,
      safeAreaData,
      deviceInfo,
      pageBackgroundColor,
      headerBackgroundColor,
      contentBackgroundColor,
      appRunState,
    },
  });
};
